/**
 * Created by kelvin.pang on 2017/6/13.
 */

var Jpang = Jpang||{}, P = Jpang, createjs = createjs||{};

var debug = false;

Jpang.extend = function(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;//super
};

(function (P) {
    'use strict';
    /**
     *
     * @param box
     * @param context
     * @param slider
     * @param parameter
     * @example
     slider(screen2b.s2bBox,
     screen2b.s2bBox.s2bContext,
     screen2b.s2bBox.slider,{
            BOX_H : 441,
            SLIDER_BG_H : 374,
            SLIDER_H : 123,
            CONTENT_H : 915
    });
     */
    P.slider = function(box,context,slider,parameter) {
        var BOX_H = parameter.BOX_H,
            SLIDER_BG_H = parameter.SLIDER_BG_H,
            SLIDER_H = parameter.SLIDER_H,
            CONTENT_H = parameter.CONTENT_H,
            propagat = parameter.propagat || false,
            SLIDER_INIT_Y = slider.y,
            CONTENT_INIT_Y = context.y;
        var F = (SLIDER_BG_H-SLIDER_H) / (CONTENT_H-BOX_H),
            minY =  BOX_H + CONTENT_INIT_Y - CONTENT_H,
            maxY_slider = SLIDER_BG_H + SLIDER_INIT_Y - SLIDER_H;
        var ifpropagat = true;
        box.addEventListener("mousedown",function(evt){
            ifpropagat = CONTENT_INIT_Y != context.y;
            !propagat && ifpropagat && evt.stopPropagation();
            context.offset = {y: context.y - evt.stageY, stageY:evt.stageY};
            slider.offset = {y: slider.y , stageY: evt.stageY};
        });
        box.addEventListener("pressmove",function(evt){
            ifpropagat = CONTENT_INIT_Y != context.y;
            !propagat && ifpropagat && evt.stopPropagation();
            if(Math.abs(evt.stageY - context.offset.stageY)>50){
                box.mouseChildren = false;
            }
            var stepY = evt.stageY + context.offset.y,
                stepY_slider = slider.offset.y + (slider.offset.stageY - evt.stageY) * F;
            context.y = stepY>CONTENT_INIT_Y ? CONTENT_INIT_Y : stepY<minY ? minY : stepY;
            slider.y = stepY_slider<SLIDER_INIT_Y ? SLIDER_INIT_Y : stepY_slider>maxY_slider ? maxY_slider : stepY_slider;
        });
        box.addEventListener("pressup",function(evt){
            !propagat && ifpropagat && evt.stopPropagation();
            box.mouseChildren = true;
        });
    };
    /*P.slider = function(box,context,slider,parameter) {
        var BOX_H = parameter.BOX_H,
            SLIDER_BG_H = parameter.SLIDER_BG_H,
            SLIDER_H = parameter.SLIDER_H,
            CONTENT_H = parameter.CONTENT_H,
            propagat = parameter.propagat || false,
            SLIDER_INIT_Y = slider.y,
            CONTENT_INIT_Y = context.y;
        var F = (SLIDER_BG_H-SLIDER_H) / (CONTENT_H-BOX_H),
            minY =  BOX_H + CONTENT_INIT_Y - CONTENT_H,
            maxY_slider = SLIDER_BG_H + SLIDER_INIT_Y - SLIDER_H;
        box.addEventListener("mousedown",function(evt){
            !propagat && evt.stopPropagation();
            context.offset = {y: context.y - evt.stageY, stageY:evt.stageY};
            slider.offset = {y: slider.y , stageY: evt.stageY};
        });
        box.addEventListener("pressmove",function(evt){
            !propagat && evt.stopPropagation();
            if(Math.abs(evt.stageY - context.offset.stageY)>50){
                box.mouseChildren = false;
            }
            var stepY = evt.stageY + context.offset.y,
                stepY_slider = slider.offset.y + (slider.offset.stageY - evt.stageY) * F;
            context.y = stepY>CONTENT_INIT_Y ? CONTENT_INIT_Y : stepY<minY ? minY : stepY;
            slider.y = stepY_slider<SLIDER_INIT_Y ? SLIDER_INIT_Y : stepY_slider>maxY_slider ? maxY_slider : stepY_slider;
        });
        box.addEventListener("pressup",function(evt){
            !propagat && evt.stopPropagation();
            box.mouseChildren = true;
        });
    };*/
    /**
     * 没滚动条的
     * @param box
     * @param context
     * @param parameter
     */
    P.slider2 = function(box,context,parameter) {
        var BOX_H = parameter.BOX_H,
            CONTENT_H = parameter.CONTENT_H,
            propagat = parameter.propagat || false,
            CONTENT_INIT_Y = context.y;
        var minY =  BOX_H + CONTENT_INIT_Y - CONTENT_H;
        box.addEventListener("mousedown",function(evt){
            !propagat && evt.stopPropagation();
            context.offset = {y: context.y - evt.stageY, stageY:evt.stageY};
        });
        box.addEventListener("pressmove",function(evt){
            !propagat && evt.stopPropagation();
            if(Math.abs(evt.stageY - context.offset.stageY)>50){
                box.mouseChildren = false;
            }
            var stepY = evt.stageY + context.offset.y;
            var exY = context.y;
            context.y = stepY>CONTENT_INIT_Y ? CONTENT_INIT_Y : stepY<minY ? minY : stepY;
            parameter.onComplete && parameter.onComplete(context.y-exY);
        });
        box.addEventListener("pressup",function(evt){
            !propagat && evt.stopPropagation();
            box.mouseChildren = true;
        });
    };
    /**
     * 获取url中的参数
     * @param name
     * @return {null}
     */
    P.getUrlParam = function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    };
    /**
     * 检查input输入的内容
     * @type {{}}
     */
    P.checkTxt = {
        trim : function(str) {
            return str.replace(/(^\s+)|(\s+$)/g, "");
        },
        name : function(str){
            return this.trim(str).length>0;
        },
        email: function (str) {
            var regex = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
            return this.trim(str).length>0 && regex.test(str);
        },
        phone: function (str) {
            var regex = /^1[0-9]{10}$/;
            return this.trim(str).length>0 && regex.test(str);
        },
        int:function (str) {//正整数
            var regex = /^[0-9]*$/;
            return this.trim(str).length>0 && regex.test(str);
        }
    };

    /**
     * video标签
     * @type {{v: {}, new: new, delect: delect}}
     */
    P.video = function(src,parameter){
        this.v={};
        parameter = parameter||{};
        this.v = document.createElement('video');
        this.v.setAttribute("src", src);//"http://p.umcgchat.com/520mideavideo.mp4"
        this.v.setAttribute("poster",  parameter.poster||'');//"images/520v.jpg"
        this.v.setAttribute("id", parameter.id||'video');
        this.v.setAttribute("width",  parameter.width||"512");
        this.v.setAttribute("height",  parameter.height||"320");
        this.v.setAttribute("controls",  parameter.controls||"true");
        this.v.setAttribute("preload",  parameter.preload||"auto");
        this.v.setAttribute("x-webkit-airplay", "allow");
        this.v.setAttribute("playsinline", "playsinline");
        this.v.setAttribute("webkit-playsinline", "webkit-playsinline");
        document.body.insertBefore(this.v, document.body.firstChild);
        this.hideVideo = function () {
            this.v.style.visibility = "hidden";
            this.v.pause();
        }.bind(this);
        this.showVideo = function () {
            this.v.style.visibility = "visible";
        }.bind(this);
        this.delect = function () {
            this.v && this.v.parentNode.removeChild(this.v);
            this.v = {};
        }
    };
    /**
     * 前补 0 操作
     * @param str
     * @param length
     * @return {string}
     */
    P.addZero = function(str,length){
        return length<str.length-1 ? str : (new Array(length - str.length + 1).join("0") + str);
    };

    /**
     * 获取屏幕宽、高
     */
    P.getWidth = function() {
        if( typeof( window.innerWidth ) == 'number' ) {
            return window.innerWidth;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            return document.documentElement.clientWidth;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            return document.body.clientWidth;
        }
    };
    P.getHeight = function() {
        if( typeof( window.innerWidth ) == 'number' ) {
            return window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            return document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientHeight || document.body.clientHeight ) ) {
            return document.body.clientHeight;
        }
    };

})(Jpang);


/**
 * 要click事件才能触发selectImage, mousedown无法触发
 * @param callback
 * @param _this
 * @example
 selectImage(function(t, imageBase64){
     console.log(t);
     console.log(imageBase64);
 },this);
 */
(function (P) {
    'use strict';
    P.selectImage = function(callback, _this, size) {
        MAX_HEIGHT = size||MAX_HEIGHT;
        selectedHandler = callback;
            thisRef = _this;
        var i = document.getElementById("fileInput");
        null == i && (i = document.createElement("input"),
            i.id = "fileInput",
            i.type = "file",
            i.accept = "image/*",
            /*i.style.height = "0px",
            i.style.display = "block",
            i.style.overflow = "hidden",*/
            i.style.cssText = "height:0px;display:block;overflow:hidden;",
            document.body.insertBefore(i, document.body.firstChild),
            i.addEventListener("change", tmpSelectFile, !1)),
            setTimeout(function() {
                i.click()
            }, 100);
    };
    function tmpSelectFile(e) {
        var file = e.target.files[0], i = file.type;
        i || (i = mime[file.name.match(/\.([^\.]+)$/i)[1]]);
        var n = myCreateObjectURL(file);
        tmpCreateImage(n, file);
        var a = document.getElementById("fileInput");
        a.value = ""
    }
    function tmpCreateImage(url, file) {
        var i = new Image;
        var n = document.createElement("canvas");
        /*this.i = i;
        this.n = n;*/
        i.onload = function () {
            if(this.width>this.height){
                this.width *= MAX_HEIGHT / this.height, this.height = MAX_HEIGHT;
            }else{
                this.height *= MAX_HEIGHT / this.width, this.width = MAX_HEIGHT;
            }
            /*var a = n.getContext("2d");
            a.clearRect(0, 0, n.width, n.height), n.width = i.width, n.height = i.height, a.drawImage(i, 0, 0, i.width, i.height);
            var base64img = n.toDataURL("image/png");
            i.width = i.height = 1;
            selectedHandler && selectedHandler(thisRef, base64img, file);*/
            getOrientation(file,function (orientation) {
                drawImageHandle(orientation,n,i);
                var base64img = n.toDataURL("image/png");
                i.width = i.height = 1;
                selectedHandler && selectedHandler(thisRef, base64img, file);
            });
        };
        i.src = url;
        i.style.visibility = "hidden";
        // i.style.display = "none"
        // document.body.appendChild(i)
    }
    function myCreateObjectURL(e) {
        return void 0 != window.URL ? window.URL.createObjectURL(e) : window.webkitURL.createObjectURL(e)
    }
    var mime = {
        png: "image/png",
        jpg: "image/jpeg",
        jpeg: "image/jpeg",
        bmp: "image/bmp"
    }, selectedHandler, thisRef, MAX_HEIGHT = 660;

    /**
     * 获取图片orientation
     * @param file
     * @param callback
     */
    function getOrientation(file,callback) {
        var orientation = null;// 1:0°; 6:顺时针90°; 8:逆时针90°; 3:180°;
        //获取照片方向角属性，用户旋转控制
        try{
            EXIF.getData(file, function() {
                EXIF.getAllTags(this);
                orientation = EXIF.getTag(this, 'Orientation');
                if(debug)console.log('Orientation:',orientation);
                // if(debug)console.log(EXIF.pretty(this));//打印全部参数
                callback(orientation);
            });
        }catch (e){
            callback(orientation);
            if(debug)console.log(e);
        }
    }
    function drawImageHandle(ori,n,img) {
        var a = n.getContext("2d");
        a.clearRect(0, 0, n.width, n.height);
        var degree;
        switch(ori){
            case 3://180°
                degree = 2*90 * Math.PI / 180;
                n.width = img.width, n.height = img.height,a.rotate(degree), a.drawImage(img, -img.width, -img.height, img.width, img.height);
                break;
            case 6://顺时针90°
                degree = 90 * Math.PI / 180;
                n.width = img.height, n.height = img.width,a.rotate(degree), a.drawImage(img, 0, -img.height, img.width, img.height);
                break;
            case 8://逆时针90°
                degree = 3*90 * Math.PI / 180;
                n.width = img.height, n.height = img.width,a.rotate(degree),a.drawImage(img, -img.width, 0, img.width, img.height);
                break;
            default:
                n.width = img.width, n.height = img.height, a.drawImage(img, 0, 0, img.width, img.height);
        }
    }

})(Jpang);


(function (P,cjs) {
    'use strict';
    /**
     * touch cotroler
     * @type {{enable: Jpang.Touch.enable, disable: Jpang.Touch.disable}}
     */
    P.Touch = {
        enable : function (stage ,allowDefault) {
            cjs.Touch.enable(stage ,false, allowDefault);
            stage.preventSelection = !allowDefault;
        },
        disable : function(stage) {
            cjs.Touch.disable(stage);
        }
    };
    P.nativeEvent = function(evt) {
        evt && evt.nativeEvent && evt.nativeEvent.preventDefault && evt.nativeEvent.preventDefault();
    };
    /**
     * 拍照，控制图片旋转
     * @param callback
     */
    (P.selectImg = function(imageBase64,callback){
        var i = new Image, _this=this;
        this.initialize(i);
        i.onload = function(){
            _this.nominalBounds = new cjs.Rectangle(0, 0,i.width,i.height);
            _this.regX = Math.round(i.width/2);
            _this.regY = Math.round(i.height/2);
            callback && callback();
        };
        // i.setAttribute('crossOrigin', 'anonymous');
        i.src = imageBase64;
    }).prototype = new cjs.Bitmap();

    var bitmap,touchPoint;

    P.actionImg = function(callback,size) {
        if(bitmap){
            bitmap.removeEventListener("mousedown",imgMouseDown);
            bitmap.removeEventListener("pressmove", imgMouseMove);
            bitmap.removeEventListener("pressup",imgMouseUp);
            bitmap = undefined;
            touchPoint = undefined;
        }
        P.selectImage(function(t, imageBase64){
            bitmap = new P.selectImg(imageBase64,function () {
                callback && callback(bitmap);
            });
            bitmap.y = bitmap.x = size/2;
            bitmap.addEventListener("mousedown",imgMouseDown);
            bitmap.addEventListener("pressmove", imgMouseMove);
            bitmap.addEventListener("pressup",imgMouseUp);
        },this,size);
    };
    var keys, _d, _cd;
    function imgMouseDown(evt) {
        P.nativeEvent(evt);
        // console.log('down');
        touchPoint = touchPoint || {};
        touchPoint[evt.pointerID]={
            x: Math.round(evt.stageX),
            y: Math.round(evt.stageY),
            a : evt,
        };
        bitmap._x = bitmap.x;
        bitmap._y = bitmap.y;
        bitmap._rotation = bitmap.rotation;
        bitmap._scale = bitmap.scaleX;
        keys = Object.keys(touchPoint);
        if(keys.length>1)_d = distance(touchPoint[keys[1]],touchPoint[keys[0]]);
    }

    function imgMouseMove(evt) {
        P.nativeEvent(evt);
        // console.log('moveeeeeeeeeeee');
        if(!touchPoint)return;
        if(keys.length==1){
            bitmap.x = Math.round(bitmap._x + evt.stageX - touchPoint[evt.pointerID].x);
            bitmap.y = Math.round(bitmap._y + evt.stageY - touchPoint[evt.pointerID].y);
        }else{
            touchPoint[evt.pointerID].a = evt;
            var p1 = {
                    x : touchPoint[keys[1]].a.stageX,
                    y : touchPoint[keys[1]].a.stageY
                },
                p2 = {
                    x:touchPoint[keys[0]].a.stageX,
                    y:touchPoint[keys[0]].a.stageY
                };
            _cd = distance(p1, p2);
            bitmap.scaleX = bitmap.scaleY = bitmap._scale * _cd/_d;
            var v1 = {
                    x : p1.x - p2.x,
                    y : p1.y - p2.y
                },
                v2 = {
                    x : touchPoint[keys[1]].x - touchPoint[keys[0]].x,
                    y : touchPoint[keys[1]].y - touchPoint[keys[0]].y
                };
            var angle = _getRotateAngle(v1, v2);
            bitmap.rotation = bitmap._rotation + angle;
        }
    }
    function imgMouseUp(evt) {
        P.nativeEvent(evt);
        // console.log('up');
        if(!touchPoint)return;
        touchPoint = undefined;
    }
    //勾股定理
    function distance(p1,p2){
        var calX = p2.x - p1.x,
            calY = p2.y - p1.y;
        return Math.sqrt(calX * calX + calY * calY);
    }
    //这两个方法属于向量计算
    function _getRotateDirection(vector1,vector2) {
        return vector1.x * vector2.y - vector2.x * vector1.y;
    }
    function _getRotateAngle(vector1,vector2) {
        var direction = _getRotateDirection(vector1,vector2);
        direction = direction > 0 ? -1 : 1;
        var len1 = Math.sqrt(vector1.x*vector1.x + vector1.y*vector1.y);
        var len2 = Math.sqrt(vector2.x*vector2.x + vector2.y*vector2.y);
        var mr = len1 * len2;
        if(mr === 0) return 0;
        var dot = vector1.x * vector2.x + vector1.y * vector2.y;
        var r = dot / mr;
        if(r > 1) r = 1;
        if(r < -1) r = -1;
        return Math.acos(r) * direction * 180 / Math.PI;
    }
})(Jpang,createjs);

/**
 * 手指滑动切换
 * @example
 * var swiper = new Jpang.swiper().init(items,mc1,{direction:'x',span:640,speed:2,loop:false,callback:_call});
 * swiper.goto(0,function (id) {});
 */
(function (P,cjs) {
    'use strict';
    P.swiper = function(){
        var tweenPlay = false, _index=-1,
            items, parent;
        var Par_Direction = 'x',//方向
            Par_Callback,//回调
            Par_speed,//过场速度
            Par_loop = false,//循环拨动
            Par_Type = 'cd',// 过场类型。'cd':重叠，'tc':同层平衡
            Par_Span = '640',//跨度
            Par_isResetReg = true;//是否重新设置regX|regY

        this.getIndex = function () {
            return _index;
        };
        this.enable = true;
        this.space = 80;//触发滑动到下一页的拨动间距
        this.init = function (pages,container,parameter) {
            if(!container)throw new Error('container not undefined.');
            items = pages || [];
            parent = container;
            if(typeof parameter=='object'){
                Par_Direction = parameter.direction || 'x';
                Par_Span = parameter.span || 640;
                Par_Callback = parameter.callback;
                Par_speed = parameter.speed || 3;
                Par_loop = parameter.loop || false;
                Par_Type = parameter.type || 'cd';
                Par_isResetReg = parameter.isResetReg==false?false:true;
            }
            for(var e in items){
                if(Par_isResetReg)items[e].setTransform(0,0,1,1,0,0,0,0,0);
                items[e].visible = false;
                items[e].id = e;
            }
            _index = 0;
            parent.addEventListener("mousedown",handleDown.bind(this));
            parent.addEventListener("pressmove",handleMove);
            parent.addEventListener("pressup",handleUp.bind(this));
        };
        this.goto = function (id,callback) {
            if(tweenPlay)return;
            var obj = items[id];
            setPosition(obj,id<_index?-Par_Span:Par_Span);
            obj.visible = true;
            obj.parent && obj.parent.addChild(obj);
            changePage(obj,function (id) {
                callback && callback(id);
                Par_Callback(id);
            });
            upObj=downObj=undefined;
        };
        this.getIndex = function () {
            return _index;
        };

        function setPosition(obj,span) {
            var minShowSpan = 30;
            if(Par_Direction=='x'){
                if(minShowSpan<Math.abs(obj.x-span))obj.x=span;
            }else{
                if(minShowSpan<Math.abs(obj.y-span))obj.y=span;
            }
            return 'p'
        }
        function changePage(_t,callback){
            tweenPlay = true;
            if(typeof items[_index].onFinish == 'function' && _t.id != _index)items[_index].onFinish();//onFinish 当前页面转为不活动状态要处理的方法
            if(typeof _t.net === 'object' && _t.id != _index)_t.net.refresh();
            var _callback=function(p){
                _index = Number(p);
                if(callback)callback(_index);
                if(typeof _t.onStart == 'function')_t.onStart();
                tweenPlay = false;
            };
            var o = Par_Direction=='x'?{x: 0}:{y: 0};
            cjs.Tween.get(_t).to(o, Par_Span/Par_speed,cjs.Ease.sineOut).call(_callback,[_t.id]);
            return 'c';
        }
        var upObj,downObj,initSpan=0;
        function handleDown(evt){
            P.nativeEvent(evt);
            // console.log('handle down');
            if(!this.enable)return;
            if(_index==-1|| tweenPlay)return;

            initSpan = Par_Direction=='x'?evt.stageX:evt.stageY;

            var up,down;
            if(Par_loop){
                up = _index==0 ? items.length-1 : _index-1;
                down = _index>=items.length-1 ? 0 : _index+1;
            }else{
                up =_index-1;
                down =_index+1;
            }
            if(up>=0){
                // upObj = items[_index==0 ? items.length-1 : _index-1];
                upObj = items[up];
                // upObj.x = -Par_Span;
                setPosition(upObj,-Par_Span);
                upObj.visible = true;
                upObj.gotoAndStop(0);
                upObj.parent && upObj.parent.addChild(upObj);
            }
            if(down<items.length){
                // downObj = items[_index>=items.length-1 ? 0 : _index+1];
                downObj = items[down];
                // downObj.x = Par_Span;
                setPosition(downObj,Par_Span);
                downObj.visible = true;
                downObj.gotoAndStop(0);
                downObj.parent && downObj.parent.addChild(downObj);
            }
            if(Par_Type=='tc'){
                var target = items[_index];
                target.offset = {x: target.x - evt.stageX, y: target.y - evt.stageY};
            }
        }
        function handleMove(evt){
            P.nativeEvent(evt);
            if(_index==-1|| tweenPlay)return;
            // console.log('handle move');
            var _d;
            var XY = Par_Direction=='x'?evt.stageX:evt.stageY;
            if(XY>initSpan){
                if(typeof upObj=='undefined')return;
                _d = XY - initSpan - Par_Span;
                // upObj.x = _d>0 ? 0 : _d;
                setPosition(upObj, _d>0?0:_d);
            }else{
                if(typeof downObj=='undefined')return;
                _d = XY - initSpan + Par_Span;
                // downObj.x = _d<0 ? 0 : _d;
                setPosition(downObj, _d<0?0:_d);
            }
            if(Par_Type=='tc'){
                var target = items[_index];
                Par_Direction=='x'? target.x = target.offset.x + XY : target.y = target.offset.y + XY;
            }
        }
        function handleUp(evt){
            P.nativeEvent(evt);
            if(_index==-1|| tweenPlay)return;
            // console.log('handle up');
            var xy, z, up=false, down=false;
            if(typeof upObj!='undefined'){
                xy = Par_Direction=='x'?upObj.x:upObj.y;
                z = xy>this.space-Par_Span ? changePage(upObj,Par_Callback) : setPosition(upObj, -Par_Span);
                up = (z=='c');
                upObj = undefined;
            }
            if(typeof downObj!='undefined'){
                xy = Par_Direction=='x'?downObj.x:downObj.y;
                z = xy<(Par_Span-this.space) ? changePage(downObj,Par_Callback) : setPosition(downObj, Par_Span);
                down = (z=='c');
                downObj = undefined;
            }
            if(Par_Type=='tc'){
                var target = items[_index];
                var value = up? Par_Span : down? -Par_Span : 0;
                var o = Par_Direction=='x'?{x: value}:{y: value};
                cjs.Tween.get(target).to(o, Par_Span/Par_speed,cjs.Ease.sineOut);
            }
        }
    };
})(Jpang,createjs);

/**
 * @example
 * mainBGM = new AudioCreate("media/bgm.mp3?1514713110064",{id:"bgm"});
 */
(function (P) {
    'use strict';
    P.AudioCreate = function (src,param) {
        param = param || {};
        var aud = document.createElement('audio');
        param.id && (aud.id=param.id);
        aud.src=src;
        aud.preload="auto";
        aud.controls=true;
        aud.hidden=true;
        aud.autoplay = param.autoplay!=false;
        if(param.loop!=false){
            aud.onended = function() {
                aud.currentTime=0;
                aud.play();
            };
        }
        /*aud.addEventListener("canplay",function (evt) {
            console.log("canplay1");
        });*/
        if (typeof WeixinJSBridge === "undefined") {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }
        // onBridgeReady();
        function onBridgeReady() {
            aud.play();
            if(param.autoplay==false) {
                var t = setTimeout(function () {
                    clearTimeout(t);
                    aud.pause();
                });
            }
        }
        this.stop = function () {
            aud.pause();
        };
        this.play = function (time) {
            if(typeof time=='number')aud.currentTime=time;
            aud.play();
        };
        this.delete = function () {
            aud.pause();
            document.removeEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            aud=null;
            param=null;
            src=null;
        };
    };
})(Jpang);

/**
 * 地图控制器
 * @param map
 * @param param
 * @constructor
 * @example
 * var MapContr = new Jpang.MapControler(map,{map_width:2734,map_height:2000,c_width:canvasWidth,c_height:canvasHeight});
 */
Jpang.MapControler = function (map,param) {

    //是否属于触发地图热点
    // this.hasHotEvent = true;
    var touchPoint, keys, _d, _cd;
    var map_width = param.map_width||100,
        map_height = param.map_height||100,
        c_width = param.c_width||100,
        c_height = param.c_height||100;
    // var THIS = this;
    map.on('mousedown', mapMouseDown);
    map.on('pressmove', mapMouseMove);
    map.on('pressup', function (evt) {
        evt.stopPropagation();
        touchPoint = undefined;
        map.mouseChildren = true;
        // THIS.hasHotEvent = true;
        var maxW = map_width * this.scaleX,//this.nominalBounds.width
            maxH = map_height * this.scaleY;//this.nominalBounds.height
        this.x = this.x > maxW / 2 ? maxW / 2 : this.x < c_width - maxW / 2 ? c_width - maxW / 2 : this.x;
        this.y = this.y > maxH / 2 ? maxH / 2 : this.y < c_height - maxH / 2 ? c_height - maxH / 2 : this.y;
    });
    /*map.x = map.regX = this.nominalBounds.width/2;
    map.y = map.regY = this.nominalBounds.height/2;*/
    map.initScale = map.scaleX;
    // mcGo.mcM.map.setTransform(0,0,1,1,0,0,0,0,0);
    // console.log('x:',mcGo.mcM.map.x,'  y:',mcGo.mcM.map.y,'  w:',mcGo.mcM.map.nominalBounds.width*mcGo.mcM.map.scaleX,' scale:',mcGo.mcM.map.scaleX);

    function mapMouseDown(evt) {
        // evt.stopPropagation();
        // console.log('down');
        touchPoint = touchPoint || {};
        touchPoint[evt.pointerID] = {
            x: Math.round(evt.stageX),
            y: Math.round(evt.stageY),
            a: evt
        };
        this.offset = {x: this.x, y: this.y, rotation: this.rotation, scale: this.scaleX};
        keys = Object.keys(touchPoint);
        if (keys.length > 1) {
            _d = distance(touchPoint[keys[1]], touchPoint[keys[0]]);
        }
    }

    function mapMouseMove(evt) {
        evt.stopPropagation();
        // console.log('moveeeeeeeeeeee');
        if (!touchPoint)return;
        if (keys.length == 1) {
            var _x = Math.round(this.offset.x + evt.stageX - touchPoint[evt.pointerID].x);
            var _y = Math.round(this.offset.y + evt.stageY - touchPoint[evt.pointerID].y);
            var maxW = map_width * this.scaleX,//this.nominalBounds.width
                maxH = map_height * this.scaleY;//this.nominalBounds.height
        } else {
            touchPoint[evt.pointerID].a = evt;
            var p1 = {
                    x: touchPoint[keys[1]].a.stageX,
                    y: touchPoint[keys[1]].a.stageY
                },
                p2 = {
                    x: touchPoint[keys[0]].a.stageX,
                    y: touchPoint[keys[0]].a.stageY
                };
            /*var L1 = this.globalToLocal(p1.x,p1.y);
             var L2 = this.globalToLocal(p2.x,p2.y);*/

            _cd = distance(p1, p2);
            this.scaleX = this.scaleY = Math.max(this.offset.scale * _cd / _d, this.initScale);

            _x = this.x, _y = this.y;

        }
        this.x = _x > maxW / 2 ? maxW / 2 : _x < c_width - maxW / 2 ? c_width - maxW / 2 : _x;
        this.y = _y > maxH / 2 ? maxH / 2 : _y < c_height - maxH / 2 ? c_height - maxH / 2 : _y;
        // console.log(this.x,'  ',this.y,'  ',this.globalToLocal(evt.stageX,evt.stageY).x*this.scaleX);

        //触发位移距离大于20就默认不是触发热点事件
        if(Math.abs(_x - this.offset.x) >= 40 || Math.abs(_y - this.offset.y) >= 40){
            map.mouseChildren = false;
        }
        // if (Math.abs(_x - this.offset.x) >= 20 || Math.abs(_y - this.offset.y) >= 20)THIS.hasHotEvent = false;
    }

    //勾股定理
    function distance(p1, p2) {
        var calX = p2.x - p1.x,
            calY = p2.y - p1.y;
        return Math.sqrt(calX * calX + calY * calY);
    }
};

(function (P,cjs) {
    "use strict";

    function DisplayDocument(type,w,h,t,l) {
        this.doc = document.createElement(type);//"img"、"input"、"textarea"
        this._width = w;
        this._height = h;
        this._top = t;
        this._left = l;
        /*this.doc.style.padding = 0;
        this.doc.style.margin = 0;
        this.doc.style.position = "absolute";
        this.doc.style.zIndex = 999;
        this.doc.style.border = "none";
        this.doc.style.visibility= 'hidden';
        this.doc.style.height = this._height +'px';
        this.doc.style.width = this._width +'px';
        this.doc.style.top = this._top +'px';
        this.doc.style.left = this._left +'px';*/
        var cssText = 'padding:0; margin:0; position:absolute; z-index:999; border:none; visibility:hidden; ';
        cssText += 'height:' + this._height +'px;';
        cssText += 'width:' + this._width +'px;';
        cssText += 'top:' + this._top +'px;';
        cssText += 'left:' + this._left +'px;';
        this.doc.style.cssText += cssText;
    }
    DisplayDocument.prototype = {
        get value(){
            return this.doc.value;
        },
        set value(val){
            this.doc.value = val;
        }
    };
    DisplayDocument.prototype.show = function () {
        this.doc.style.visibility= 'visible';
    };
    DisplayDocument.prototype.hide = function () {
        this.doc.style.visibility= 'hidden';
    };
    DisplayDocument.prototype.resize = function (canvas) {
        /*
         bottom         :         1050
         height         :         1050
         left         :         0
         right         :         646
         top         :         0
         width         :         646
         x         :         0
         y         :         0
         */
        //获取document标签缩放后的实际宽高,位置等信息
        var rect = canvas.getBoundingClientRect();
        var wf = rect.width/canvas.width, hf = rect.height/canvas.height;
        /*this.doc.style.left = (this._left * wf) +rect.left +'px';
        this.doc.style.width = this._width * wf +'px';
        this.doc.style.top = (this._top * hf) +rect.top +'px';
        this.doc.style.height = this._height * hf +'px';*/
        var cssText = 'height:' + (this._height * hf) +'px;';
        cssText += 'width:' + (this._width * wf) +'px;';
        cssText += 'top:' + ((this._top * hf) +rect.top) +'px;';
        cssText += 'left:' + ((this._left * wf) +rect.left) +'px;';
        this.doc.style.cssText += cssText;
    };

    function Text(type,txt,param) {
        if(!(txt instanceof cjs.Text))throw new Error("txt type must is cjs.Text!");
        var param = param||{};
        var fonts = txt.font.split("px "),//"26px 'Adobe Heiti Std R'"
            bounds = txt.getBounds();
        var p1 = txt.parent.localToGlobal(txt.x,txt.y);
        var w = txt.lineWidth,
            h = param.height || txt.lineHeight,
            t = p1.y +bounds.y -txt.regY,
            l = p1.x +bounds.x -txt.regX;
            if(txt.textAlign=="center")
            l -= (w - bounds.width)/2;
        DisplayDocument.call(this,type,w,h,t,l); //super();
        this._fontSize = fonts[0];
        this.doc.value = param.value||'';
        this.doc.placeholder = param.placeholder||'';
        txt.text = '';
        if(param.native && typeof param.native=='object'){
            for(var i in param.native) {
                if(Object.prototype.hasOwnProperty.call(param.native,i)) { //过滤
                    this.doc.setAttribute(i,param.native[i]);//添加标签属性
                }
            }
        }//end if

        /*this.doc.style.background = "transparent";
        this.doc.style.outline = "none";
        this.doc.style.color = txt.color;
        this.doc.style.font = fonts[1];
        this.doc.style.fontSize = this._fontSize +'px';
        this.doc.style.textAlign = txt.textAlign;*/
        var cssText = 'background:transparent; outline:none; ';
        cssText += 'color:'+ txt.color;
        cssText += ';font:'+ fonts[1];
        cssText += ';font-size:' + this._fontSize +'px;';
        cssText += 'text-align:' + txt.textAlign +';';
        this.doc.style.cssText += cssText;

        txt = null;
        param = null;
    }
    P.extend(Text,DisplayDocument);
    Text.prototype.resize = function (canvas) {
        DisplayDocument.prototype.resize.call(this,canvas);
        var rect = canvas.getBoundingClientRect();
        var hf = rect.height/canvas.height;
        this.doc.style.fontSize = this._fontSize * hf +'px';
    };

    /**
     * 根据createjs Text对象生成对应document input标签
     * @type {Text}
     * @example
     *  var input = new P.InputText(exportRoot.txt,canvas,{type:"text",placeholder:'input content',
	 		native:{maxlength:11, onkeyup:"this.value=this.value.replace(/[^0-9]/g,'')", onafterpaste:"this.value=this.value.replace(/[^0-9]/g,'')"}
	 	});
     */
    P.InputText = function (cjsTxt,canvas, param) {
        Text.call(this,'input',cjsTxt,param);
        param.type && (this.doc.type = param.type);
        this.resize(canvas);
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
    };
    P.extend(P.InputText,Text);

    /**
     * 根据createjs Text对象生成对应document textarea标签
     * @type {Text}
     * @example
     * new P.Textarea(exportRoot.txt2,canvas,{height:191,placeholder:'textarea content'});
     */
    P.Textarea = function (cjsTxt,canvas, param) {
        Text.call(this,'textarea',cjsTxt,param);
        this.doc.style.resize = "none";
        this.resize(canvas);
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
    };
    P.extend(P.Textarea,Text);

    /**
     * 根据createjs MovieClip对象生成对应document img标签
     * @type {Text}
     * @example
     * new P.QRcode(qrcodeobj,canvas,{src:'qrcode.jpg'});
     */
    P.QRcode = function(obj,canvas,param) {
        // if(!(obj instanceof cjs.Bitmap))throw new Error("obj type must is cjs.Bitmap!");
        var param = param||{};
        var bounds = obj.getBounds();
        var p1 = obj.parent.localToGlobal(obj.x,obj.y);
        var w = bounds.width,
            h = param.height || bounds.height,
            t = p1.y +bounds.y -obj.regY,
            l = p1.x +bounds.x -obj.regX;
        DisplayDocument.call(this,"img",w,h,t,l); //super();
        this.doc.src = param.src;
        obj = null;
        param = null;
        canvas.parentNode.insertBefore(this.doc, canvas.parentNode.firstChild);
        this.resize(canvas);
    };
    P.extend(P.QRcode,DisplayDocument);

})(Jpang,createjs);